package com.ruoyi.web.fileDemo;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @Program: RuoYi-Vue-chy->copyFileDemo
 * @Description: 异常处理办法，不同的jdk
 * @Author: hongyu.chen
 * @Date: 2025-03-08 13:33
 * @Version： 1.0
 **/
public class copyFileDemo {
    public static void main(String[] args) {

    }

    //jdk9的改进方案
    private static void method4() throws IOException {
        FileReader fr = new FileReader( "fr.txt");
        FileWriter fw = new FileWriter(  "fw.txt");
        try (fr;fw){
            char[] chs = new char[1024];
            int len;
            while((len=fr.read())!=-1){
                fw.write(chs, 0,len);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }


    //jdk7的改进方案
    private static void method3() {
        try (FileReader fr = new FileReader( "fr.txt");
             FileWriter fw = new FileWriter(  "fw.txt");){


            char[] chs = new char[1024];
            int len;
            while((len=fr.read())!=-1){
                fw.write(chs, 0,len);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    //try....catch...finally
    private static void method2() {
        FileReader fr = null;
        FileWriter fw = null;
        try {

            fr = new FileReader( "fr.txt");
            fw = new FileWriter(  "fw.txt");

            char[] chs = new char[1024];
            int len;
            while((len=fr.read())!=-1){
                fw.write(chs, 0,len);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {

            if(fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(fr!=null){

                try {
                    fr.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    private static void methodl() throws IOException {
        FileReader fr = new FileReader( "fr.txt");
        FileWriter fw = new FileWriter(  "fw.txt");

        char[] chs = new char[1024];
        int len;
        while((len=fr.read())!=-1){
            fw.write(chs, 0,len);
        }
        fw.close();
        fr.close();
    }
}